package com.fuhaixing.modules.web;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.fuhaixing.modules.entity.Currency;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.List;

/**导出汇率信息
 * @author FHX
 * @Date 2021-02-25  11:51
 * @describe CurrencyController
 */
@RestController
@RequestMapping(value = "currency")
public class CurrencyController {
    @Autowired
    private RobotCurrencyController robotCurrencyController;

    /**
     * 导出汇率信息
     * @param response
     * @param erectDate
     * @param nothing
     * @param pjname
     * @param pageSize
     * @param fileType
     * @throws ParseException
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "export")
    public void exportStudentInfos(HttpServletResponse response, String erectDate, String nothing, String pjname, int pageSize, String fileType) throws ParseException, UnsupportedEncodingException {
        // 设置响应类型
        response.setContentType("application/vnd.ms-excel");
        // 设置字符编码
        response.setCharacterEncoding("utf-8");
        // 设置响应头信息(2007版Excel后缀为.xls,其他版本为.xlsx)
        response.setHeader("Content-disposition",
                "attachment;filename*=utf-8''" + URLEncoder.encode(pjname + "汇率信息表", "UTF-8") + "." + fileType);

        List<Currency> currencyList = robotCurrencyController.getRobot(erectDate, nothing, pjname, pageSize, fileType);

        // 写入文件
        ExcelWriter writer = ExcelUtil.getWriter();
//        writer.addHeaderAlias("sno", "编号");
        writer.addHeaderAlias("currencyName", "货币名称");
        writer.addHeaderAlias("spotBuyPrice", "现汇买入价");
        writer.addHeaderAlias("cashBuyPrice", "现钞买入价");
        writer.addHeaderAlias("spotSellPrice", "现汇卖出价");
        writer.addHeaderAlias("cashSellPrice", "现钞卖出价");
        writer.addHeaderAlias("discountPrice", "中行折算价");
        writer.addHeaderAlias("releaseTime", "发布时间");
        writer.write(currencyList, true);
        try {
            writer.flush(response.getOutputStream(), true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }
}
